// 一个进度条插件
import { AppService } from "@/service/app-service";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {
  registerMicroApps,
  addGlobalUncaughtErrorHandler,
  start,
} from "qiankun";

// 子应用注册信息
import apps from "./apps";

/**
 * 注册子应用
 * 第一个参数 - 子应用的注册信息
 * 第二个参数 - 全局生命周期钩子
 */
registerMicroApps(apps, {
  // qiankun 生命周期钩子 - 加载前
  beforeLoad: (app: any) => {
    console.log('加载前----', app);
    const loadContainer = document.getElementById('child-container-loading');
    if (loadContainer) {
      loadContainer.style.cssText = "display: block;";
    }
    NProgress.start();
    return Promise.resolve();
  },
  // qiankun 生命周期钩子 - 挂载后
  afterMount: (app: any) => {
    console.log('挂载后----', app);
    const loadContainer = document.getElementById('child-container-loading');
    if (loadContainer) {
      loadContainer.style.cssText = "display: none;";
    }
    NProgress.done();
    AppService.getInstance().addMountedMicroApp(app);
    return Promise.resolve();
  },
  // qiankun 生命周期钩子 - 销毁前
  beforeUnmount: (app: any) => {
    AppService.getInstance().removeMountedMicroApp(app);
    return Promise.resolve();
  }
});

/**
 * 添加全局的未捕获异常处理器
 */
addGlobalUncaughtErrorHandler((event: Event | string) => {
  console.error(event);
  const { message: msg } = event as any;
  // 加载失败时提示
  if (msg && msg.includes("died in status LOADING_SOURCE_CODE")) {
    console.error("子应用加载失败，请检查应用是否可运行");
  }
});

// 导出 qiankun 的启动函数
export default start;
